package com.recsmile.controller;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.recsmile.mapper.SecUserMapper;

@Controller
public class UserManagerController {

	@Autowired
	private SecUserMapper secUserMapper;
	
	@Autowired
	private SecurityManager securityManager;
	
	@PostConstruct
	public void afterCreate(){
		SecurityUtils.setSecurityManager(securityManager);
	}
	
	@RequestMapping("/addUser")
	public void addUser(HttpServletRequest request, Model model){
		//secUserMapper.insert(record);
	}
	
	@RequestMapping("/login")
	public String login(HttpServletRequest request, Model model){
		String userName = request.getParameter("form-username");
		String password = request.getParameter("form-password");
		UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
		try {
			Subject subject = SecurityUtils.getSubject();
			subject.login(token);
			if (subject.isAuthenticated()) {
	            return "redirect:success"; 
			}
		} catch (IncorrectCredentialsException e) {
			model.addAttribute("msg", "登录密码错误. Password for account " + token.getPrincipal() + " was incorrect.");
		}catch (ExcessiveAttemptsException e) {
			model.addAttribute("msg", "登录失败次数过多.");
		}catch (LockedAccountException e) {
			model.addAttribute("msg", "帐号已被锁定. The account for username " + token.getPrincipal() + " was locked.");
		}catch (DisabledAccountException e) {
			model.addAttribute("msg", "帐号已被禁用. The account for username " + token.getPrincipal() + " was disabled.");
		}catch (ExpiredCredentialsException e) {
			model.addAttribute("msg",  "帐号已过期. the account for username " + token.getPrincipal() + "  was expired.");
		}catch (UnknownAccountException e) {
			model.addAttribute("msg", "帐号不存在. There is no user with username of " + token.getPrincipal());
		}catch (UnauthorizedException e) {
			model.addAttribute("msg", "您没有得到相应的授权！" + e.getMessage());
		}
		return "login";
	}
}
